package us.mifeng.basicvp.network.exception

import com.google.gson.JsonSyntaxException
import retrofit2.HttpException
import java.net.ConnectException
import java.net.SocketTimeoutException

object ErrorHandler {
    fun handleError(throwable: Throwable): Throwable {
        return when (throwable) {
            is HttpException -> {
                when (throwable.code()) {
                    401 -> ApiException(401, "未授权")
                    403 -> ApiException(403, "禁止访问")
                    404 -> ApiException(404, "资源不存在")
                    500 -> ApiException(500, "服务器内部错误")
                    else -> ApiException(throwable.code(), "网络错误: ${throwable.code()}")
                }
            }
            is SocketTimeoutException -> ApiException(-1, "连接超时")
            is ConnectException -> ApiException(-1, "网络连接失败")
            is JsonSyntaxException -> ApiException(-1, "数据解析错误")
            is ApiException -> throwable
            else -> ApiException(-1, "未知错误: ${throwable.message}")
        }
    }
}    